package q6_threadpool_test;

/*
什么是死锁？
    死锁是指两个或两个以上的进程在执行过程中，因争夺资源而造成的一种互相等待的现象，若无外力干涉，那它们都将无法推进下去。
    如果系统资源充足，进程的资源请求都能够得到满足，死锁出现的可能性就很低，否则就会因争夺有限的资源而陷入死锁。

如何定位并解决
1、jps命令定位进程编号
> jps -l

5272 q6_threadpool_test.DeadLockDemo

2、jstack找到死锁查看
>jstack 5272

Java stack information for the threads listed above:
===================================================
"BBB":
        at q6_threadpool_test.HoldLockThread.run(DeadLockDemo.java:31)
        - waiting to lock <0x000000076b713270> (a java.lang.String)
        - locked <0x000000076b7132a8> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)
"AAA":
        at q6_threadpool_test.HoldLockThread.run(DeadLockDemo.java:31)
        - waiting to lock <0x000000076b7132a8> (a java.lang.String)
        - locked <0x000000076b713270> (a java.lang.String)
        at java.lang.Thread.run(Thread.java:748)

Found 1 deadlock.
*/

import java.util.concurrent.TimeUnit;

class HoldLockThread implements Runnable {
    private String lockA;
    private String lockB;

    public HoldLockThread(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA) {
            System.out.println(Thread.currentThread().getName() + "\t自己持有：" + lockA + "\t尝试获得：" + lockB);
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB) {
                System.out.println(Thread.currentThread().getName() + "\t自己持有：" + lockB + "\t尝试获得：" + lockA);
            }
        }
    }
}

public class DeadLockDemo {

    public static void main(String[] args) {

        String lockA = "lockA";
        String lockB = "lockB";

        new Thread(new HoldLockThread(lockA, lockB), "AAA").start();
        new Thread(new HoldLockThread(lockB, lockA), "BBB").start();
    }

}
